//
//  ChargingEventViewController.m
//  Runone
//
//  Created by runone01 on 16/8/31.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "ChargingEventViewController.h"
#import "ParModel.h"
#import "StationRrportModel.h"
#import "RequestHelper.h"
#import "MJExtension.h"
#import "SGImagePickerController.h"
#import "EventTypeTableViewController.h"
#import "UUDatePicker.h"
#import "POPDatePickViewController.h"
#import "CommonUtilityjudge.h"
#import "PromptUtil.h"
#import "DateViewController.h"
#import "AFNetworking.h"
#import "BCNetAPIClient.h"
#import "StationListPopViewController.h"
#import "UIView+Message.h"
#import "UITextField+ToolBar.h"
#import "UITextView+ToolBar.h"
//#import "UIColor+ZXLazy.h"
#import "SVProgressHUD.h"

@interface ChargingEventViewController ()<UIPopoverPresentationControllerDelegate,UITextViewDelegate,UITextFieldDelegate,UIAlertViewDelegate>
//输入控件
@property (weak, nonatomic) IBOutlet UITextField *StationTF;
@property (weak, nonatomic) IBOutlet UITextField *EventType;
@property (weak, nonatomic) IBOutlet UITextField *monitorTF;
@property (weak, nonatomic) IBOutlet UITextField *EventTimeTF;
@property (weak, nonatomic) IBOutlet UIButton *TimeBtn;
@property (weak, nonatomic) IBOutlet UITextView *DesCription;
@property (weak, nonatomic) IBOutlet UIButton *imageBtn;
@property (weak, nonatomic) IBOutlet UIButton *VideoBtn;
@property (weak, nonatomic) IBOutlet UIScrollView *imageScrollView;

//弹出视图+类+控制器
@property(nonatomic,strong)DateViewController *dateVC;
@property(nonatomic,strong)StationListPopViewController *station;
@property(nonatomic,strong)EventTypeTableViewController *eventVC;
@property(nonatomic,strong) StationRrportModel *StationModel;
@property(nonatomic,strong)POPDatePickViewController *popdate;
@property(nonatomic,strong)PromptUtil *Prompt;
@property(nonatomic,strong)UIAlertView *alert;

//返回结果
@property(nonatomic)NSInteger code;

//Scrollview选图
@property(nonatomic,strong)UIImageView *iv;
@property(nonatomic,strong)UIImage *img;
@property(nonatomic,strong)NSArray *imageArray;
@property(nonatomic,strong)UIImage *loadImage;

//Message
@property(nonatomic,strong)UIView *MessageView;
@property(nonatomic,strong)UIAlertView *resultAlert;
@end

@implementation ChargingEventViewController

#pragma     --------事件上报

- (void)viewDidLoad {
    [super viewDidLoad];
    [self dropBtn];
    [self datePick];
    [self stationListBtn];
    [self TFCantEdit];
    [self TFInputOK];
   // self.view.backgroundColor=[UIColor colorWithHexString:@"#f7f7f7"];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(report)];
    _StationModel=[[StationRrportModel alloc] init];
    _station=[[StationListPopViewController alloc] init];
    _station.modalPresentationStyle=UIModalPresentationPopover;
    __weak typeof(self) stationSelf = self;
    _station.LineBlock=^(StationModel *model){
        stationSelf.StationTF.text=[NSString stringWithFormat:@"%@",model.TollStationName];
        stationSelf.StationModel.TollStationUID=model.TollStationUID;
    };
    
    _Prompt=[[PromptUtil alloc] init];
    _DesCription.delegate=self;
    NSLog(@"创建一次");
    UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    label.text=@"收费事件上报";
    label.textAlignment=NSTextAlignmentCenter;
    label.textColor=[UIColor whiteColor];
    self.navigationItem.titleView=label;
    _eventVC=[[EventTypeTableViewController alloc] init];
    _eventVC.modalPresentationStyle=UIModalPresentationPopover;
}

-(void)TFInputOK
{
    [_monitorTF setTextFieldInputAccessoryView:_monitorTF frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    _monitorTF.clearButtonMode=UITextFieldViewModeAlways;
    
    [_DesCription setTextFieldInputAccessoryView:_DesCription frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    
}

-(void)resultMessage:(NSString *)result
{
    _resultAlert=[[UIAlertView alloc] initWithTitle:@"提示" message:result delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [_resultAlert show];
}
-(void)TFCantEdit
{
    _StationTF.delegate=self;
    _EventType.delegate=self;
    _EventTimeTF.delegate=self;
}

-(void)stationListBtn
{
    
    UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    
    _StationTF.rightView=btn;
    [btn addTarget:self action:@selector(dropStationList:) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundImage:[UIImage imageNamed:@"xiala"] forState:UIControlStateNormal];
    _StationTF.rightViewMode=UITextFieldViewModeAlways;
}

-(void)dropStationList:(UIButton *)btn
{
    _station.popoverPresentationController.sourceView=btn;
    _station.popoverPresentationController.delegate=self;
    _station.popoverPresentationController.sourceRect=CGRectMake(0, -5, -55, 265);
    _station.popoverPresentationController.permittedArrowDirections=NO;
    [self presentViewController:_station animated:YES completion:nil];
    
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return NO;
}

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([_DesCription.text isEqualToString:@"请输入事件描述："]) {
        _DesCription.text=@"";
        _DesCription.textColor=[UIColor blackColor];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.text.length<1) {
        textView.text = @"请输入事件描述：";
        textView.textColor=[UIColor grayColor];
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden=NO;
}

-(void)dropBtn
{
    
    UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [btn setBackgroundImage:[UIImage imageNamed:@"xiala"] forState:UIControlStateNormal];
    self.EventType.rightView=btn;
    [btn addTarget:self action:@selector(drop:) forControlEvents:UIControlEventTouchUpInside];
    _EventType.rightViewMode=UITextFieldViewModeAlways;
}
-(void)drop:(UIButton *)btn
{
    _eventVC.popoverPresentationController.sourceView=btn;
    _eventVC.popoverPresentationController.delegate=self;
    _eventVC.popoverPresentationController.sourceRect=CGRectMake(-20, 109, 0, 0);
    _eventVC.popoverPresentationController.permittedArrowDirections=NO;
    [self presentViewController:_eventVC animated:YES completion:nil];
    
}

-(void)datePick
{
    _dateVC=[[DateViewController alloc] init];
    _dateVC.modalPresentationStyle=UIModalPresentationPopover;
    _dateVC.popoverPresentationController.sourceView=self.view;
    _dateVC.popoverPresentationController.sourceRect=DateFrame;
    _dateVC.popoverPresentationController.permittedArrowDirections=NO;
    _dateVC.popoverPresentationController.delegate=self;

}


-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}

-(void)request
{
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getCurrentEventModel=[[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL=GetEventDataURL;
    getCurrentEventModel.DataValue = [self dataValueJson];
    getCurrentEventModel.UpdatedTime=[self GetUpdateTime];
    getCurrentEventModel.SystemCode=@"GuangleHighway";
    getCurrentEventModel.MethodName=@"ReportTollStationEventDetailInfo";
    
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        
        NSLog(@"%@",dataValueModel);
        self.code=[requestOutginseng.Code integerValue];
        if (_code==001) {
            [SVProgressHUD showSuccessWithStatus:@"上报成功"];
            [self.navigationController popViewControllerAnimated:YES];
            //[self resultMessage:@"上报成功"];
        }
        else
        {
            [SVProgressHUD showSuccessWithStatus:@"上报失败"];
            //[_Prompt alert:@"其他问题，请稍后再试"];
            return;
        }
    };
    if (!_loadImage) {
        [requestHelper RequestGinsengModel:getCurrentEventModel andPushController:self];
    }
    else
    {
        [self requestTestUpdateImage:getCurrentEventModel Image:_loadImage];

  //   [requestHelper requestTestUpdateImage:getCurrentEventModel Image:_loadImage];
    }
}
//附件图片
-(void)requestTestUpdateImage:(RequestGinsengModel *)RequestGinseng Image:(UIImage *)LoadImage
{
    [SVProgressHUD showWithStatus:@"正在上传图片,请稍后......"];
    UIImage *image = LoadImage;
    
    NSDictionary *dic=[[NSDictionary alloc] init];
    
    dic=@{@"methodName":RequestGinseng.MethodName,@"updatedtime":RequestGinseng.UpdatedTime,@"systemcode":DefaultSystemCode,@"DataValue":RequestGinseng.DataValue};
    
    [BCNetAPIClient  uploadImage:GetEventDataURL andParameters:dic andImage:image progress:^(NSProgress *progress) {
        
    }success:^(id responseObject)
     {
         [SVProgressHUD showSuccessWithStatus:@"上报成功"];
         [self.navigationController popViewControllerAnimated:YES];
     }
                         failure:^(NSError *failure) {
                             [SVProgressHUD showSuccessWithStatus:@"上报失败"];
                              NSLog(@"%@",failure);
                             return ;
                            
                         }];
}

-(NSString *)GetUpdateTime
{
    NSDate *date=[NSDate date];
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSString *time=[format stringFromDate:date];
    return time;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0) {
        NSLog(@"0");
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(NSString *)dataValueJson
{
    
    if ([self.EventType.text isEqualToString:@"收费事件"]) {
        _StationModel.EventType=@"1";
    }
    if ([self.EventType.text isEqualToString:@"冲卡事件"]) {
        _StationModel.EventType=@"2";
    }
    if ([self.EventType.text isEqualToString:@"现场纠纷"]) {
        _StationModel.EventType=@"3";
    }
    //    _StationModel.EventType=@"1";
    _StationModel.DutyMonitor=self.monitorTF.text;
    _StationModel.OccurTime=self.EventTimeTF.text;
    _StationModel.EventDescription=self.DesCription.text;
    _StationModel.TollStationName=self.StationTF.text;
    
    
    NSMutableDictionary *dic=_StationModel.mj_keyValues;
    NSString *modelStr=[dic mj_JSONString];
    
    ParModel *model=[[ParModel alloc] init];
    model.key=@"TollStationEventInfo";
    model.value=modelStr;
    
    NSMutableDictionary *jsonDic=model.mj_keyValues;
    NSString *json=[jsonDic mj_JSONString];
    
    NSString *str=@"[";
    NSString *temp=[str stringByAppendingString:json];
    NSString *str1=@"]";
    NSString *JsonString=[temp stringByAppendingString:str1];
    
    return JsonString;
}
- (void)report{
    if (stringIsEmpty(_StationTF.text)) {
        _MessageView=MessageViewFrame;
        [_MessageView prompt:@"请选择收费站"];
        [self.view addSubview:_MessageView];
        return;
    }
    if (stringIsEmpty(_EventType.text)) {
        [_Prompt alert:@"请输入事件类型"];
        return;
    }
    if (stringIsEmpty(_monitorTF.text)) {
        [_Prompt alert:@"请输入值班站长"];
        return;
    }
    if (stringIsEmpty(_EventTimeTF.text)) {
        [_Prompt alert:@"请输入发生时间"];
        return;
    }
    if (stringIsEmpty(_DesCription.text)) {
        [_Prompt alert:@"请输入事件描述"];
        return;
    }
    if ([_DesCription.text isEqualToString:@"请输入事件描述："])
    {
        [_Prompt alert:@"请输入事件描述"];
    }
    
    [self request];
    
}
- (IBAction)timeBtnClick:(id)sender {
    [self datePick];
    __weak typeof(self) weakSelf=self;
    [self datePick];
    _dateVC.dateBlock=^(NSString *str){
        weakSelf.EventTimeTF.text=str;
    };
    
    [self presentViewController:_dateVC animated:YES completion:nil];
}

- (IBAction)EventTimeFieldClick {
    
}
- (IBAction)uploadImage:(UIButton *)sender {
    
    if (_imageScrollView) {
        for (UIView *subView in _imageScrollView.subviews) {
            [subView removeFromSuperview];
        }
    }
    
    SGImagePickerController *picker = [[SGImagePickerController alloc] initWithRootViewController:self];
    
    //返回选择的缩略图
    [picker setDidFinishSelectThumbnails:^(NSArray *thumbnails) {
        _imageArray=thumbnails;
        for (int i=0;i<_imageArray.count;i++) {
            _img=_imageArray[i];
            //_loadImage=thumbnails[i];
            
            _iv=[[UIImageView alloc] initWithFrame:CGRectMake(2+(125+2)*i, 0, 125, 125)];
            _iv.image=_img;
            [_imageScrollView addSubview:_iv];
        }
        _imageScrollView.contentSize=CGSizeMake(thumbnails.count*125, 125);
        NSLog(@"缩略图%@",thumbnails);
        
    }];
    
    //返回选中的原图
    [picker setDidFinishSelectImages:^(NSArray *images) {
        for (int i=0;i<_imageArray.count;i++) {
            _loadImage=images[i];
        }
        NSLog(@"原图%@,%lu",images,(unsigned long)images.count);
    }];
    [self presentViewController:picker animated:YES completion:nil];

}

-(void)uploadImage
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].，
 // Pass the selected object to the new view controller.
 }
 */

@end
